package com.hs.mod_archive.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.VERTICAL
import com.hs.framework.base.BaseDataBindFragment
import com.hs.framework.utils.Speech
import com.hs.framework.utils.ValidateUtils
import com.hs.mod_archive.R
import com.hs.mod_archive.databinding.DialogEditCabinetBinding
import com.hs.mod_archive.databinding.FragmentArchiveManagerBinding
import com.hs.mod_archive.view.DialogUtil
import com.hs.mod_archive.view.MyDialog
import com.hs.room.model.archive.Archive
import com.hs.room.model.archive.ArchiveLevel
import com.hs.room.model.archive.ArchiveType
import com.hs.room.model.archive.DevCabinet
import com.hs.room.model.dto.ArchiveCabinetDto
import com.hs.room.repository.service.IArchiveDictRepository
import com.hs.room.repository.service.IArchiveRepository
import com.hs.room.repository.service.IDevRepository
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import javax.inject.Inject

@AndroidEntryPoint
class FragmentArchiveManager : BaseDataBindFragment<FragmentArchiveManagerBinding>() {
    private var archives: List<Archive>? = null
    private var cabinets: List<DevCabinet>? = null
    private lateinit var level: List<ArchiveLevel>
    private lateinit var type: List<ArchiveType>
    private var datas: List<DevCabinet>? = null

    @Inject
    lateinit var dictService: IArchiveDictRepository

    lateinit var names: MutableList<String>
    var dialog: MyDialog? = null
    var dialogBinding: DialogEditCabinetBinding? = null

    @Inject
    lateinit var service: IDevRepository

    @Inject
    lateinit var archiveService: IArchiveRepository
    override fun initView(view: View, savedInstanceState: Bundle?) {
        mBinding!!.labelPagerHeader.bannerTvTitle.setText(R.string.archiveManager)
        mBinding!!.labelPagerHeader.bannerTvBack.setOnClickListener { navigateUp() }
        val gridLayoutManager = GridLayoutManager(activity, 4, VERTICAL, false)
        mBinding!!.recyclerView.setLayoutManager(gridLayoutManager)

    }

    override fun initData() {
        super.initData()
        lifecycleScope.launch {
            service.getDevCabinet()
                .collect {
                    cabinets = it
                    setAdapter()
                }
        }
        lifecycleScope.launch {
            archiveService.getArchive(0, 1000).collect {
                archives = it
                setAdapter()
            }
        }

        lifecycleScope.launch {
            dictService.getType(0, 100).collect {
                var m = listOf(ArchiveType(0, 0, "忽略", "", 0, "0", true))
                m = m.toMutableList()
                m.addAll(it)
                type = m
            }
        }
        lifecycleScope.launch {
            dictService.getLevel(0, 100).collect {
                var mlist = listOf(ArchiveLevel(0, 0, "忽略", "", 0, "0", true))
                mlist = mlist.toMutableList()
                mlist.addAll(it)
                level = mlist
            }
        }
    }

    private fun setAdapter() {

        var list = mutableListOf<ArchiveCabinetDto>()
        var map = mutableMapOf<String, MutableList<Archive>>()
        if (null != archives)
            for (archive in archives!!) {
                if (map.containsKey("${archive.boardId}_${archive.lockID}")) {
                    map.get("${archive.boardId}_${archive.lockID}")!!.add(archive)
                } else {
                    map.put("${archive.boardId}_${archive.lockID}", mutableListOf(archive))
                }
            }
        if (null != cabinets) {
            names = mutableListOf()
            for (cabinet in cabinets!!) {
                names.add(cabinet.name)
                list.add(
                    ArchiveCabinetDto(
                        cabinet,
                        map.get("${cabinet.boardId}_${cabinet.lockNo}")
                    )
                )
            }
        }
        mBinding!!.recyclerView.adapter = MyAdapter(list)
    }

    inner class MyAdapter(private val dataList: List<ArchiveCabinetDto>) :
        RecyclerView.Adapter<MyAdapter.ViewHolder>() {

        inner class ViewHolder(i: View) : RecyclerView.ViewHolder(i) {
            val v1: TextView = i.findViewById(R.id.tv_type_value)
            val v2: TextView = i.findViewById(R.id.tv_file_total_value)
            val v3: TextView = i.findViewById(R.id.tv_file_total_in_cabinet_value)
            val v4: TextView = i.findViewById(R.id.bt_edit)
            val v5: TextView = i.findViewById(R.id.bt_open)
            val v6: TextView = i.findViewById(R.id.bt_manage)
            val v7: TextView = i.findViewById(R.id.tv_title)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.item_archive_manager, parent, false)
            return ViewHolder(view)
        }

        override fun onBindViewHolder(h: ViewHolder, p: Int) {
            h.v7.text = dataList[p].cabinet.name
            if (dataList[p].archives != null) {
                h.v2.text = dataList[p].archives!!.size.toString()
            } else {
                h.v2.text = "0"
            }
            h.v4.setOnClickListener { showEdit(dataList[p].cabinet) }
            h.v5.setOnClickListener { openDoor(dataList[p].cabinet) }
            h.v5.setOnClickListener { goArchiveManager(dataList[p].cabinet) }


//            h.v2.text = dataList[p].name
//            h.v3.text = dataList[p].name
//            h.v4.text = dataList[p].name
//            h.v5.text = dataList[p].name
//            h.v6.text = dataList[p].name
        }


        override fun getItemCount() = dataList.size
    }

    private fun goArchiveManager(cabinet: DevCabinet) {


    }

    private fun showEdit(dd: DevCabinet) {
        val d = dd.clone()
        if (null == dialogBinding) {
            dialogBinding = DialogEditCabinetBinding.inflate(layoutInflater)
        }
        // 设置适配器
        val adapter =
            ArrayAdapter(requireActivity(), android.R.layout.simple_spinner_item, type)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        dialogBinding!!.type.adapter = adapter
        for (i in type.indices) {
            if (d.archiveType == type[i].localId) {
                dialogBinding!!.type.setSelection(i)
                break
            }
        }

        // 设置适配器
        val adapter1 =
            ArrayAdapter(requireActivity(), android.R.layout.simple_spinner_item, level)
        adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        dialogBinding!!.level.adapter = adapter1
        for (i in level.indices) {
            if (d.archiveLevel == level[i].localId) {
                dialogBinding!!.level.setSelection(i)
                break
            }
        }
        dialogBinding!!.name.setText(d.name)
        dialogBinding!!.bID.setText(d.boardId.toString())
        dialogBinding!!.remark.setText(d.remark)
        dialogBinding!!.bNo.setText("${d.lockNo} ")
//        if (d.runningIndicator) {
//            dialogBinding!!.runningIndicator.isChecked = true
//            when (d.color) {
//                0 -> dialogBinding!!.rbR.isChecked = true
//                1 -> dialogBinding!!.rbG.isChecked = true
//                2 -> dialogBinding!!.rbB.isChecked = true
//            }
//        } else {
//            dialogBinding!!.runningIndicator.isChecked = false
//        }

        // 设置选择监听器
        dialogBinding!!.btSubmit.setOnClickListener { _ ->
            if (!ValidateUtils.notNull(
                    dialogBinding!!.name,
                    getString(R.string.name)
//                ) || !ValidateUtils.notNull(
//                    dialogBinding!!.bID,
//                    getString(R.string.lockBoard)
//                ) || !ValidateUtils.notNull(
//                    dialogBinding!!.bNo,
//                    getString(R.string.lockNo)
//                ) || !ValidateUtils.notNull(
//                    dialogBinding!!.lID,
//                    getString(R.string.lampBoard)
//                ) || !ValidateUtils.notNull(
//                    dialogBinding!!.lNo,
//                    getString(R.string.lampNo)
                )
            ) {
                return@setOnClickListener
            }
            val name: String = dialogBinding!!.name.text.toString().trim()
            if (!name.equals(d.name) && names.contains(name)) {
                Speech.speak(getString(R.string.nameExist))
                return@setOnClickListener
            }
//            val bid: String = dialogBinding!!.bID.text.toString().trim()
//            val bno: String = dialogBinding!!.bNo.text.toString().trim()
//            val lid: String = dialogBinding!!.lID.text.toString().trim()
//            val lno: String = dialogBinding!!.lNo.text.toString().trim()
            val l: String = dialogBinding!!.level.selectedItem.toString()
            val t: String = dialogBinding!!.type.selectedItem.toString()
            var levelId = 0L
            level.forEach {
                if (l.equals(it.alName)) {
                    levelId = it.localId
                }
            }
            var typeId = 0L
            type.forEach {
                if (t.equals(it.atName)) {
                    typeId = it.localId
                }
            }
            d.name = name
            d.archiveLevel = levelId
            d.archiveType = typeId
            d.remark = dialogBinding!!.remark.text.toString().trim()
            update(
                d
            )
        }
        val root: ConstraintLayout = dialogBinding!!.getRoot()
        val parent = root.parent
        if (null != parent) {
            val viewGroup = parent as ViewGroup
            viewGroup.removeView(root)
            dialogBinding!!.name.setText("")
            dialogBinding!!.bID.setText("")
            dialogBinding!!.bNo.setText("")
//            dialogBinding!!.lID.setText("")
//            dialogBinding!!.lNo.setText("")
        }
        dialogBinding!!.btClose.setOnClickListener { _ -> dismissDialog() }
        dialogBinding!!.btCancel.setOnClickListener { _ -> dismissDialog() }
        //-------------------------
        val w = resources.getDimensionPixelSize(R.dimen.dp_582)
        val h = resources.getDimensionPixelSize(R.dimen.dp_482)
        dialog = DialogUtil.buildSpecialView(activity, root, w, h, false, false)

    }

    fun dismissDialog() {
        dialog?.dismiss()
        dialog = null
        dialogBinding = null
    }

    fun update(src: DevCabinet) {
        dismissDialog()
        lifecycleScope.launch {
            service.update(src)
        }
    }

    private fun openDoor(cabinet: DevCabinet) {


    }
}
